package me.thinkjet.sso.client.filter;

import java.io.IOException;

import javax.servlet.FilterChain;
import javax.servlet.FilterConfig;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import me.thinkjet.sso.client.util.CommonUtils;
import me.thinkjet.sso.client.util.HttpUtils;
import me.thinkjet.sso.client.validation.Assertion;

public class AuthenticationFilter extends AbstractFilter {

    private String serverLoginUrl;

    protected void initInternal(final FilterConfig filterConfig)
	    throws ServletException {
	if (!isIgnoreInitConfiguration()) {
	    super.initInternal(filterConfig);
	    setServerLoginUrl(getPropertyFromInitParams(filterConfig,
		    "serverLoginUrl", null));
	}
    }

    public void init() {
	super.init();
	CommonUtils.assertNotNull(this.serverLoginUrl,
		"serverLoginUrl cannot be null.");
    }

    public final void doFilter(final ServletRequest servletRequest,
	    final ServletResponse servletResponse, final FilterChain filterChain)
	    throws IOException, ServletException {
	final HttpServletRequest request = (HttpServletRequest) servletRequest;
	final HttpServletResponse response = (HttpServletResponse) servletResponse;
	final HttpSession session = request.getSession(false);
	final Assertion assertion = session != null ? (Assertion) session
		.getAttribute(CONST_SSO_ASSERTION) : null;

	if (assertion != null) {
	    filterChain.doFilter(request, response);
	    return;
	}

	final String serviceUrl = constructServiceUrl(request, response);
	final String ticket = HttpUtils.safeGetParameter(request,
		getTicketName());
	if (CommonUtils.isNotBlank(ticket)) {
	    filterChain.doFilter(request, response);
	    return;
	}

	final String urlToRedirectTo = HttpUtils.constructRedirectUrl(
		this.serverLoginUrl, getServiceName(), serviceUrl);

	response.sendRedirect(urlToRedirectTo);
    }

    public final void setServerLoginUrl(final String serverLoginUrl) {
	this.serverLoginUrl = serverLoginUrl;
    }

}
